package com.sgb.kjwl.view.ui.fragment.transport.company;

import android.graphics.Color;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.android.arouter.launcher.ARouter;
import com.fondesa.recyclerviewdivider.DividerDecoration;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.sgb.kjwl.AppLazyFragment;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.FragAffManageBinding;
import com.sgb.kjwl.model.entity.transport.AffiliatedFDetailsListEntity;
import com.sgb.kjwl.model.entity.transport.AffiliatedFDriverEntity;
import com.sgb.kjwl.view.constant.RouterKey;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.event.self.GoodsManageEvent;
import com.sgb.kjwl.view.ui.adapter.self.logistics.AffiliatedFDetailsAdapter;
import com.sgb.kjwl.viewmodel.transport.AffiliatedFDetailsModel;
import com.sgb.link.router.PathDriver;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.util.ArrayUtil;

import org.greenrobot.eventbus.EventBus;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * author:熊丽
 * createDate:2021/10/15 10:55
 * introduce:
 * modifier:xxx
 * modifiyDate:
 * modifiyContent:
 */
public class AffiliatedFDetailsFragment  extends AppLazyFragment {
    //货源列表
    private AffiliatedFDetailsAdapter mAdapter;
    //
    private boolean isTable,isSelf;//isTable 表示TAB标签为true 表示是共享车辆  isSelf表示是否是自营车队详情
    private int mPattern;
    private int mPage = 1;
    FragAffManageBinding binding;
    AffiliatedFDetailsModel viewModel;
    private List<AffiliatedFDriverEntity> driverList = new ArrayList<>();
    private String no;
    public static AffiliatedFDetailsFragment newInstance( boolean isTable,boolean isSelf,String no,List<AffiliatedFDriverEntity> driverList) {
        AffiliatedFDetailsFragment fragment = new AffiliatedFDetailsFragment();
        Bundle args = new Bundle();
        args.putBoolean(RouterKey.BOOLEAN, isTable);
        args.putBoolean("isSelf", isSelf);
        args.putString(RouterKey.STRING,no);
        args.putSerializable(RouterKey.DATA, (Serializable) driverList);
        fragment.setArguments(args);
        return fragment;
    }
    @Override
    protected void setupFragmentComponent(AppComponent appComponent) {
        viewModel = new ViewModelProvider(this).get(AffiliatedFDetailsModel.class);
    }
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.frag_aff_manage, container, false);
        binding.setLifecycleOwner(this);
        return binding.getRoot();
    }

    @Override
    protected void onLazyLoad() {
        initIntentParams();
        initRecycler();
        initEvent();
        initData();
    }
    private void initIntentParams() {
        Bundle bundle = getArguments();
        if (bundle != null) {
            isTable = getArguments().getBoolean(RouterKey.BOOLEAN, false);
            isSelf = getArguments().getBoolean("isSelf", false);
            no = getArguments().getString(RouterKey.STRING);
            driverList = (List<AffiliatedFDriverEntity>) getArguments().getSerializable(RouterKey.DATA);
        }
    }
    private void initRecycler() {
        mAdapter = new AffiliatedFDetailsAdapter(driverList);
        binding.rvCargoManage.setLayoutManager(new LinearLayoutManager(getActivity()));
        if (getActivity() != null) {
            DividerDecoration.builder(getActivity())
                    .showFirstDivider()
                    .colorRes(R.color.color_f5f5f5)
                    .size(5, TypedValue.COMPLEX_UNIT_PX)
                    .build()
                    .addTo(binding.rvCargoManage);
        }
        mAdapter.bindToRecyclerView(binding.rvCargoManage);
        if (ArrayUtil.isNullOrEmpty(driverList)) {
            setEempty();
        }else {
            binding.viewBackgroundWhite.setVisibility(View.GONE);
            binding.rlContent.setVisibility(View.GONE);
            binding.srlCargoManage.setVisibility(View.VISIBLE);
        }
        mAdapter.setOnItemClickListener((adapter, view, position) -> {
            AffiliatedFDriverEntity info = driverList.get(position);

        });
    }
    private void initEvent() {
        binding.srlCargoManage.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                mPage++;
                viewModel.getDriverList(getActivity(),no,mPage,isSelf?1:2);
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                refreshData();
            }
        });
        mAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            AffiliatedFDriverEntity info = driverList.get(position);
            itemClick(view, info);
        });
        //接口回调
        viewModel.ldDriverList.observe(this, this::refreshUIByData);
    }

    private void initData() {
        refreshData();
    }

    /**
     * 列表按钮点击事件
     */
    private void itemClick(View view, AffiliatedFDriverEntity info) {
        if (view.getId() == R.id.cl_item_cm) {
            if (isSelf){
                ARouter.getInstance().build(PathDriver.ProprietaryDriverDetailsActivity)
                        .withString(RouterKey.ID, info.getNo())
                        .navigation(getContext());
            }
        }
    }

    public void refreshData() {
        if (mAdapter != null) {
            mPage = 1;
            viewModel.getDriverList(getActivity(),no,mPage,isSelf?1:2);
        }
    }
    private void setListData(AffiliatedFDetailsListEntity mlist){
        if (mlist==null){
           setEempty();
            return;
        }else {
            EventBus.getDefault().post(GoodsManageEvent.make(EventConstant.EVENT_REFRESH_AFFILIATED_DATA, mlist));
        }
    }
    private void setEempty(){
        binding.rlContent.setVisibility(View.VISIBLE);
        binding.srlCargoManage.setVisibility(View.GONE);
        binding.viewBackgroundWhite.setVisibility(View.VISIBLE);
        if (isSelf){
            if (!isTable){
                binding.noDataTv.setText("该车队暂无司机");
                binding.noDataCount.setText("请至司机管理中“添加司机");
                binding.noDataCount.setVisibility(View.VISIBLE);
                binding.noDataCount.setTextColor(Color.parseColor("#969696"));
                binding.noDataTv.setTextColor(Color.parseColor("#969696"));
            }else {
                binding.noDataTv.setText("该车队暂无司机");
                binding.noDataCount.setVisibility(View.VISIBLE);
                binding.noDataCount.setText("添加司机后，绑定司机的车辆归属于该车队");
                binding.noDataCount.setTextColor(Color.parseColor("#666666"));
                binding.noDataTv.setTextColor(Color.parseColor("#969696"));
            }
        }
    }
    /**
     * 同步数据
     */
    private void refreshUIByData(List<AffiliatedFDriverEntity> driverList1) {
        binding.srlCargoManage.finishRefresh();
        binding.srlCargoManage.finishLoadMore();
        if (mPage ==1){
            if (ArrayUtil.isNullOrEmpty(driverList1)) {
                setEempty();
            }else {
                binding.viewBackgroundWhite.setVisibility(View.GONE);
                binding.rlContent.setVisibility(View.GONE);
                binding.srlCargoManage.setVisibility(View.VISIBLE);
            }
            if (driverList1==null&&driverList1.size()==0){
                driverList.clear();
                return;
            }else {
                driverList.clear();
            }
            driverList.addAll(driverList1);
        }else {
            if (driverList1==null){
                binding.srlCargoManage.finishLoadMoreWithNoMoreData();
            }else {
                driverList.addAll(driverList1);
            }
        }
        mAdapter.notifyDataSetChanged();
    }

}
